package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"img-text-mgr/cache"
	"img-text-mgr/models"
	"strconv"
	"time"
)

func Create(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	picture := c.PostForm("picture")
	if title == "" || content == "" || picture == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Img{
		Title:   title,
		Content: content,
		Picture: picture,
	}
	redis_key := "img_create_" + strconv.Itoa(int(data.ID))
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Debug().Create(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Second*10)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var imgs []models.Img
	redis_key := "img_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Order("created_at desc").Find(&imgs)
		jsonData, _ := json.Marshal(imgs)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &imgs)
	}
	var total int64
	models.DB.Model(&models.Img{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"data":  imgs,
		"msg":   "success",
		"total": total,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var img models.Img
	redis_key := "img_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id = ?", id).Find(&img)
		jsonData, _ := json.Marshal(img)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &img)
	}
	var total int64
	models.DB.Model(&models.Img{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"data":  img,
		"msg":   "success",
		"total": total,
	})
	return
}
